package com.example.config;



import com.example.service.LoginUserService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;

import javax.annotation.Resource;
import javax.sql.DataSource;

@Configuration
public class SecurityConfig   {  //extends WebSecurityConfigurerAdapter

    @Resource
    LoginUserService userService;

    //老玩法
    /**
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/login").permitAll()
                .anyRequest().hasRole("user")
                .and()
                .formLogin();
    }

     @Override
     protected void configure(AuthenticationManagerBuilder auth) throws Exception {
     auth
     .userDetailsService(service)
     .passwordEncoder(new BCryptPasswordEncoder());
     }

     */

    @Resource
    DataSource  dataSource;

    //新玩法
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    /**
     -- 创建记录rememberme记录的表
     CREATE TABLE persistent_logins
     (
     username  VARCHAR(64),
     series   VARCHAR(64),
     token     VARCHAR(64),
     last_used DATETIME
     );

     */


    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{
        return http
                .authorizeRequests()
                .antMatchers("/static/**").permitAll()
                .anyRequest().hasAnyRole("user", "admin")
                .and()
                .formLogin()
                .loginPage("/login")
                .defaultSuccessUrl("/", true)
                .loginProcessingUrl("/doLogin")
                .permitAll()
                .and()
                .rememberMe()
                .tokenRepository(new JdbcTokenRepositoryImpl(){{setDataSource(dataSource);setCreateTableOnStartup(false);}})
                .and()
                .userDetailsService(userService)
                .build();

    }






}
